<template>
  <div class="app-container">
    <el-row>
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form
          :inline="true"
          v-show="showSearch"
          label-width="140px"
          :label-position="isPhone ? 'top' : 'left'"
        >
          <el-form-item label="姓名" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入姓名"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="学校" prop="trainUniversity">
            <el-select
              v-model="queryParams.trainUniversity"
              placeholder="请选择学校"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in university"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专业" prop="trainMajor">
            <el-input
              v-model="queryParams.trainMajor"
              placeholder="请输入专业"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="培养单位" prop="trainDeptName">
            <el-input
              v-model="queryParams.trainDeptName"
              placeholder="请输入培养单位"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="入企实践开始时间" prop="practiceStartYear">
            <el-select
              v-model="queryParams.practiceStartYear"
              placeholder="请选择年份"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="year in yearOptions"
                :key="year"
                :label="year + '年'"
                :value="year"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="handleGetList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="list"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="姓名"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
            width="100"
          />
          <el-table-column
            label="学校"
            align="center"
            key="trainUniversity"
            prop="trainUniversity"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              {{ getUniversityText(scope.row.trainUniversity) }}
            </template>
          </el-table-column>
          <el-table-column
            label="专业"
            align="center"
            key="trainMajor"
            prop="trainMajor"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="培养单位"
            align="center"
            key="trainDeptName"
            prop="trainDeptName"
            v-if="columns[4].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="入企时间"
            align="center"
            key="aa1"
            prop="aa1"
            v-if="columns[5].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <!-- <el-table-column
            label="月度计划"
            align="center"
            key="monthlyPlan"
            v-if="columns[6].visible"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              {{ scope.row.progressDetails?.length || 0 }}个计划
            </template>
          </el-table-column> -->
          <el-table-column
            label="操作"
            align="center"
            width="150"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="详情" placement="top">
                <el-button
                  link
                  type="info"
                  icon="View"
                  @click="handleDetail(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip>
              <!-- <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip> -->
              <!-- <el-tooltip
                content="提交"
                placement="top"
                v-if="
                  scope.row.approvalStatus === 'no_submit' ||
                  scope.row.approvalStatus === 'rejected'
                "
              >
                <el-button
                  link
                  type="warning"
                  icon="Upload"
                  @click="handleSubmit(scope.row)"
                  v-hasRole="['admin', 'student']"
                ></el-button>
              </el-tooltip> -->
              <el-tooltip
                content="审批"
                placement="top"
                v-if="scope.row.approvalAuth"
              >
                <el-button
                  link
                  type="success"
                  icon="Check"
                  @click="handleApprove(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleGetList"
        />
      </el-col>
    </el-row>
    <el-dialog
      v-if="planDialogInfo"
      v-model="planDialogVisible"
      @close="
        planDialogVisible = false;
        planDialogInfo = null;
      "
      title="计划列表"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-table :data="planDialogInfo.planDetails" style="width: 100%">
        <el-table-column label="计划名称" prop="planName" />
        <el-table-column label="计划月份" prop="planMonth">
          <template #default="scope">
            {{ scope.row.planMonth ? formatMonth(scope.row.planMonth) : "-" }}
          </template>
        </el-table-column>
        <el-table-column label="开始时间" prop="planStartTime" />
        <el-table-column label="结束时间" prop="planEndTime" />
        <el-table-column label="实践目标" prop="planTarget" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button
              type="primary"
              @click="handleSelectPlan(scope.row)"
              :disabled="['in_progress'].some(t => t === scope.row.approvalStatus)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            @click="
              planDialogVisible = false;
              planDialogInfo = null;
            "
            >关闭</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EnterprisePracticeProgress">
import {
  getList,
  delItem,
  getCurrentPlan,
} from "@/api/enterprise-practice-progress";
import { getStudentList } from "@/api/common";
import { useRouter } from "vue-router";
import moment from "moment";
import { isPhone } from "@/utils/index";
import { yearOptions } from "@/utils/constant";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { university } = proxy.useDict("university");

const list = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: true },
  { key: 1, label: `姓名`, visible: true },
  { key: 2, label: `学校`, visible: true },
  { key: 3, label: `专业`, visible: true },
  { key: 4, label: `培养单位`, visible: true },
  { key: 5, label: `入企时间`, visible: true },
  { key: 6, label: `月度计划`, visible: true },
]);

function formatMonth(monthValue) {
  if (!monthValue) return "";
  const date = new Date(monthValue);
  return `${date.getFullYear()}年${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}月`;
}

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickName: undefined,
    trainUniversity: undefined,
    trainMajor: undefined,
    trainDeptName: undefined,
    practiceStartYear: undefined,
  },
});

const { queryParams } = toRefs(data);

const userList = ref([]);

/** 查询用户列表 */
function handleGetList() {
  loading.value = true;
  getList(queryParams.value).then((res) => {
    loading.value = false;
    list.value = res.rows;
    total.value = res.total;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  handleGetList();
}

function resetQuery() {
  queryParams.value.nickName = undefined;
  queryParams.value.trainUniversity = undefined;
  queryParams.value.trainMajor = undefined;
  queryParams.value.trainDeptName = undefined;
  queryParams.value.practiceStartYear = undefined;
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + id + '"的数据项？')
    .then(function () {
      return delItem(id);
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/user/export",
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`
  );
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 高校名称文本显示函数
const getUniversityText = (universityValue) => {
  if (!universityValue) return "未知";
  const dict = university.value?.find((item) => item.value === universityValue);
  return dict ? dict.label : universityValue;
};

const planDialogInfo = ref(null);
const planDialogVisible = ref(false);
const mode = ref("");
const canEditIndex = ref(-1);

/** 修改按钮操作 */
function handleUpdate(row) {
  mode.value = "edit";
  getCurrentPlan(row.id).then((response) => {
    planDialogInfo.value = response.data;
    // 弹窗展示计划列表，选择对应的计划然后跳转
    planDialogVisible.value = true;
    const planDetails = response.data.planDetails;
    // canEditIndex.value = planDetails?.findIndex(
    //   (t) =>
    //     moment(t.planStartTime).isBefore(moment()) &&
    //     moment(t.planEndTime).isAfter(moment())
    // );
    canEditIndex.value = planDetails?.findIndex((t) =>
      moment(t.planEndTime).isAfter(moment())
    );
  });
}

/** 详情操作 */
function handleDetail(row) {
  mode.value = "view";
  getCurrentPlan(row.id).then((response) => {
    planDialogInfo.value = response.data;
    // 弹窗展示计划列表，选择对应的计划然后跳转
    planDialogVisible.value = true;
  });
}

/** 审批操作 */
function handleApprove(row) {
  mode.value = "approve";
  getCurrentPlan(row.id).then((response) => {
    planDialogInfo.value = response.data;
    // 弹窗展示计划列表，选择对应的计划然后跳转
    planDialogVisible.value = true;
  });
}

function handleSelectPlan(row) {
  console.log(row);

  router.push({
    path: `/enterprise-practice-progress/edit/${row.id}`,
    query: { mode: mode.value },
  });
}

handleGetList();
getStudentList({ roleKey: "student" }).then((res) => {
  userList.value = res.data;
});
</script>
